package com.graduation.smartparkingplatform.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtils {

  /** 秘钥：需要妥善保存，一旦泄露token有可能被破解 */
  private static final String SECRET = "This is Skygray's program";
  /** 签名算法：推荐使用HMAC256 */
  private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);
  /** 设置默认过期时间 1000*60*60=3600000=1h */
  private static String EXPIRE_DATE;

  @Value("${MyToken.expireDate}")
  public void setYmlValue(String expireDate) {
    JwtUtils.EXPIRE_DATE = expireDate;
  }

  //  private static Long EXPIRE_DATE = Long.valueOf(ymlValue);
  // 3600000L

  /**
   * 获取token信息
   *
   * @param claimMap 自定义的条件
   * @return token令牌
   */
  public static String getToken(Map<String, String> claimMap) {
    return getToken(claimMap, Long.parseLong(EXPIRE_DATE));
  }

  /**
   * @param claimMap 自定义条件
   * @param expire 过期时间 单位：毫秒
   * @return token令牌
   */
  public static String getToken(Map<String, String> claimMap, Long expire) {
    JWTCreator.Builder builder = JWT.create();
    // payload
    claimMap.forEach(builder::withClaim);
    builder.withIssuedAt(new Date(System.currentTimeMillis()));
    builder.withExpiresAt(new Date(System.currentTimeMillis() + expire));
    return builder.sign(ALGORITHM);
  }

  /**
   * 获取拦截器的Boolean
   *
   * @param token token令牌
   * @return Boolean
   */
  public static Boolean ItprVerifyToken(String token) {
    try {
      JWTVerifier verifier = JWT.require(ALGORITHM).build();
      // 验证JWT
      DecodedJWT decodedJWT = verifier.verify(token);
      return true;
    } catch (Exception e) {
      return false;
    }
  }

  /**
   * 判断客户端状态
   *
   * @param algorithm 指定算法
   * @param token token令牌
   * @return Boolean
   */
  public static Boolean clientVerifyToken(Algorithm algorithm, String token) {
    String iss = JWT.require(algorithm).build().verify(token).getClaim("iss").asString();
    String cilent = JWT.require(algorithm).build().verify(token).getClaim("cilent").asString();
    return iss.equals("smart_parking_platform") && cilent.equals("true");
  }

  /**
   * 获取DecodedJWT
   *
   * @param token token令牌
   * @return adminVerifyToken
   */
  public static Boolean adminVerifyToken(String token) {
    // 验证JWT
    String admin = JWT.require(ALGORITHM).build().verify(token).getClaim("admin").asString();
    return admin.equals("true");
  }
}
